package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.entity.Product;
import cn.tedu.coolshark.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
public class ProductController {
    @Value("${dirPath}")
    private String dirPath;
    @Autowired(required = false)
    ProductMapper mapper;
    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product){
        System.out.println("product = " + product);
        /*mapper.insert(product);*/
        //设置商品的发布时间为当前系统时间
        product.setCreated(new Date());
        //调用mapper里的insert方法
        mapper.insert(product);
    }

    @RequestMapping("/product/select")
    public List<Product> select(){
       return mapper.select();
    }



    @RequestMapping("/product/delete")
    public void delete(int id){
        //通过ID查询到商品的图片路径
        String url = mapper.selectUrlById(id);
        //获取图片的磁盘路径
        String filePath = dirPath+"/"+url;
        //删除数组中的数据
        new File(filePath).delete();
        //删除数据库里的数据
        mapper.deleteById(id);
    }

    @RequestMapping("/product/select/index")
    public List<Product> selectIndex(){
        return mapper.selectIndex();
    }

    @RequestMapping("/product/select/top")
    public List<Product> selectTop(){
       List<Product> list = mapper.selectTop();
       for(Product p: list){
           if(p.getTitle().length()>4){
              String title= p.getTitle().substring(0,4)+"...";
              p.setTitle(title);
           }
       }
        return list;
    }

    @RequestMapping("/product/select/category")
    public List<Product> selectByCid(int cid){
        return mapper.selectByCid(cid);
    }

    @RequestMapping("/search")
    public List<Product> select(String wd){
        System.out.println("wd = " + wd);
        return mapper.selectByWd(wd);
    }
    @RequestMapping("/searchByCid")
    public List<Product> select(Integer cid,String wd){
        System.out.println("cid = " + cid + ", wd = " + wd);
        return mapper.selectByIdWd(cid,wd);
    }


    @RequestMapping("/product/selectById")
    public Product selectById(int id){
        //让浏览量+1
        mapper.updateViewCount(id);
        return mapper.selectById(id);
     }

}
